<script setup lang="ts">
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import userApi from '@/api/modules/user'

const userStore = useUserStore()

const ruleFormRef = ref()
const dialogVisible = ref(false)
const ruleForm = reactive({
  accountCode: '',
  oldPassword: '',
  newPassword: '',
  newPasswordAgain: '',
})
const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  newPasswordAgain: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== ruleForm.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    }],
}
const loading = ref(false)

function open() {
  dialogVisible.value = true
  nextTick(() => {
    ruleForm.accountCode = userStore.userInfo.AccountCode
    ruleForm.oldPassword = ''
    ruleForm.newPassword = ''
    ruleForm.newPasswordAgain = ''
  })
}

function close() {
  dialogVisible.value = false
}

async function submit() {
  try {
    await ruleFormRef.value.validate()
    loading.value = true
    await userApi.UpdatePassword({
      accountCode: ruleForm.accountCode,
      oldPassword: ruleForm.oldPassword,
      newPassword: ruleForm.newPassword,
    })
    loading.value = false
    ElMessage.success('修改成功，请重新登录')
    setTimeout(() => {
      userStore.logout()
    }, 1500)
  }
  catch (e) {
    loading.value = false
  }
}

defineExpose({
  open,
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="700" draggable>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="账户名" prop="accountCode">
        <el-input v-model="ruleForm.accountCode" disabled />
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="ruleForm.oldPassword" clearable type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="ruleForm.newPassword" clearable type="password" />
      </el-form-item>
      <el-form-item label="再次输入" prop="newPasswordAgain">
        <el-input v-model="ruleForm.newPasswordAgain" clearable type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          :loading="loading"
          @click="close"
        >
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="submit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
